﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using Outlook.WorkItems.Extension.Manager;
using Outlook.WorkItems.Extension.Managers;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System.Globalization;

namespace Outlook.WorkItems.Extension.Controls
{
    public partial class TeamTreeView : UserControl
    {
        public TeamTreeView()
        {
            InitializeComponent();
            CheckChildNode = true;
        }

        public bool ShowReport { get; set; }
        public bool ShowDocumentLibrairies { get; set; }
        public bool ShowQuery { get; set; }
        public bool ShowFile { get; set; }
        public bool ShowCheckBoxes { get; set; }
        public bool CheckChildNode { get; set; }
        public string TeamProjectName { get; set; }
        bool isInternalCheck = false;

        public void InitTreeView()
        {
            try
            {
                treeView1.Nodes.Clear();
                treeView1.CheckBoxes = ShowCheckBoxes;
                List<FavoriteTeamProject> favorites = FavoritesTeamProjectManager.GetFavoritesProjects();

                var favoritesGrouped = favorites.GroupBy(f => f.TeamServerName);
                foreach (var gp in favoritesGrouped)
                {
                    TeamServerNode serverNode = new TeamServerNode(gp.Key);
                    treeView1.Nodes.Add(serverNode);
                    foreach (var favorite in gp)
                    {
                        if (string.IsNullOrEmpty(TeamProjectName))
                        {
                            serverNode.Nodes.Add(new TeamProjectNode(favorite, ShowReport, ShowDocumentLibrairies, ShowQuery, ShowFile));
                        }
                        else if (favorite.TeamProjectName == TeamProjectName)
                        {
                            serverNode.Nodes.Add(new TeamProjectNode(favorite, ShowReport, ShowDocumentLibrairies, ShowQuery, ShowFile));
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                using (ErrorForm frm = new ErrorForm(ex))
                {
                    frm.ShowDialog();
                }
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            List<FavoriteTeamProject> favorites = FavoritesTeamProjectManager.GetFavoritesProjects();
            using (TeamProjectPicker picker = new TeamProjectPicker(TeamProjectPickerMode.MultiProject, false))
            {
                foreach (var item in favorites.GroupBy(f => f.TeamServerUri))
                {
                    
                    TfsTeamProjectCollection s = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(item.Key));
                    picker.SelectedTeamProjectCollection = s;
                    var wis = s.GetService<Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore>();
                    List<ProjectInfo> list = new List<ProjectInfo>();
                    foreach (var project in item)
                    {
                        Microsoft.TeamFoundation.WorkItemTracking.Client.Project p = wis.Projects[project.TeamProjectName];
                        ProjectInfo pi = new ProjectInfo(p.Uri.ToString(), p.Name, ProjectState.WellFormed);
                        list.Add(pi);
                    }
                    picker.SelectedProjects = list.ToArray();
                }
                if (picker.ShowDialog() == DialogResult.OK)
                {
                    var projectToDelete = favorites.Where(fav => !picker.SelectedProjects.Any(p => p.Name == fav.TeamProjectName)).Distinct().ToList();
                    var projectToAdd = picker.SelectedProjects.Where(p => !favorites.Any(fav => fav.TeamProjectName == p.Name)).Distinct().ToList();

                    foreach (var project in projectToDelete)
                    {
                        FavoritesTeamProjectManager.RemoveFavoriteProject(project);
                    }
                    foreach (var project in projectToAdd)
                    {
                        FavoriteTeamProject favorite = new FavoriteTeamProject();
                        //ProjectInfo p = picker.SelectedProjects[0];
                        favorite.TeamProjectName = project.Name;
                        favorite.TeamServerName = picker.SelectedTeamProjectCollection.Name;
                        favorite.TeamServerUri = picker.SelectedTeamProjectCollection.Uri.ToString();
                        var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(favorite.TeamServerUri));
                        IRegistration registration = tfs.GetService<IRegistration>();
                        RegistrationEntry[] entries = registration.GetRegistrationEntries(RegistrationUtilities.RosettaName);

                        foreach (ServiceInterface si in entries[0].ServiceInterfaces)
                        {
                            if (si.Name == "BaseReportsUrl")
                                favorite.RServerAlternativeAddress = si.Url;
                            if (si.Name == "ReportsService")
                                favorite.RServiceAlternativeAddress = si.Url;
                        }

                        RegistrationEntry[] entriesWss = registration.GetRegistrationEntries("Wss");

                        foreach (ServiceInterface si in entriesWss[0].ServiceInterfaces)
                        {
                            if (si.Name == "BaseSiteUrl")
                                favorite.WssAlternativeAddress = si.Url;
                        }

                        FavoritesTeamProjectManager.AddFavoriteProject(favorite);
                    }
                    InitTreeView();
                }
            }
        }
        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (isInternalCheck || !CheckChildNode)
                return;

            isInternalCheck = true;

            foreach (var item in e.Node.Nodes.FindNodes(n => true))
            {
                item.Checked = e.Node.Checked;
            }

            isInternalCheck = false;
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            InitTreeView();
        }

        private void areasAndIterationsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode is TeamProjectNode)
            {
                using (AreaPathIterationForm frm = new AreaPathIterationForm(((TeamProjectNode)treeView1.SelectedNode).TeamServerUrl, ((TeamProjectNode)treeView1.SelectedNode).TeamProjectName))
                {
                    frm.ShowDialog(this);
                }
            }
        }

        private void projectAlertsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode is TeamProjectNode)
            {
                string serverUrl = ((TeamProjectNode)treeView1.SelectedNode).TeamServerUrl;
                string projectName = ((TeamProjectNode)treeView1.SelectedNode).TeamProjectName;
                var server = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(serverUrl));
                AlertSettings.ShowDialog(serverUrl, projectName, server.GetService<WorkItemStore>());
            }
        }

        private void showToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode is TeamProjectNode)
            {
                string serverUrl = ((TeamProjectNode)treeView1.SelectedNode).TeamServerUrl;
                string projectName = ((TeamProjectNode)treeView1.SelectedNode).TeamProjectName;
                var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(serverUrl));
                IRegistration registration = tfs.GetService<IRegistration>();
                RegistrationEntry[] entriesWss = registration.GetRegistrationEntries("Wss");
                string projectportal = null;
                foreach (ServiceInterface si in entriesWss[0].ServiceInterfaces)
                {
                    if (si.Name == "BaseSiteUrl")
                        projectportal = si.Url;
                }
                if (!string.IsNullOrEmpty(projectportal))
                {
                    projectportal = string.Format(CultureInfo.InvariantCulture, "{0}/sites/{1}", projectportal, projectName);
                }
            }
        }
    }
}
